package org.micode.common.syslog;

import org.micode.common.enums.OperationModeEnum;
import org.micode.common.utils.BeanExtUtils;
import org.micode.common.utils.JsonUtils;
import org.micode.common.domain.base.BaseUserCache;
import org.micode.common.domain.vo.SysLogVO;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractSysLogSaver<T extends SysLogVO> implements ISysLogSaver<T> {

    private Class<T> clazz;

    public AbstractSysLogSaver(Class<T> clazz) {
        this.clazz = clazz;
//        Type superclass = getClass().getGenericSuperclass();
//        ParameterizedType parameterizedType = null;
//        if (superclass instanceof ParameterizedType) {
//            parameterizedType = (ParameterizedType) superclass;
//            Type[] typeArray = parameterizedType.getActualTypeArguments();
//            if (typeArray != null && typeArray.length > 0) {
//                clazz = (Class<T>) typeArray[0];
//            }
//        }
    }

    @Override
    public void save(T sysLogVO) {
        log.info(sysLogVO.toString());
    }

    @Override
    public void logLogout(String moduleId,
                          BaseUserCache optUser,
                          Integer userType,
                          String remoteIp,
                          String remoteApp) {
        T sysLogVO = BeanExtUtils.instantiateClass(clazz);
        sysLogVO.setOperationMode(OperationModeEnum.NORMAL);
        sysLogVO.setOperation("Logout");

        sysLogVO.setUserType(userType);

        //请求的方法名
        String className = "LoginService";
        String methodName = "userLogout";
        sysLogVO.setMethod(className + "." + methodName + "()");
        sysLogVO.setOriginateModule(moduleId);

        //请求的参数
        String params = JsonUtils.toJson(optUser);
        sysLogVO.setParams(params);

        sysLogVO.setUserId(optUser.getUserId());
        sysLogVO.setUserToken(optUser.readUserToken());
        sysLogVO.setOriginateApp(remoteApp);
        sysLogVO.setOriginateIp(remoteIp);

        sysLogVO.setConsumeMs(0L);

        fillLogByUserCacheByLogout(sysLogVO, optUser);

        //保存系统日志
        save(sysLogVO);
    }

    protected abstract void fillLogByUserCacheByLogout(T sysLogVO, BaseUserCache optUser);

    @Override
    public abstract String getRemoteIp(Object[] args);

}
